// pages/rivercruise/rivercruise.js
var time; //定时器
var util = require("../../utils/util.js")
var api = require("../../utils/api.js")
var QQMapWX = require('../../utils/qqmap/qqmap-wx-jssdk.js');
var qqmapsdk;
let app = getApp();
let a = false;
var village_LBS = function(that) {
    //var that = this;
    // ------------ 腾讯LBS地图  --------------------
    wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function(res) {
            // 调用接口, 坐标转具体位置 -xxz0717
            that.setData({
                longitude: res.longitude,
                latitude: res.latitude,
            })
            var data = {
                long: res.longitude,
                lat: res.latitude,
                state: that.data.choushui
            }
            var url = app.u.H + app.u.river.INDEX
            api.requestUrl(data, url).then(res => {
                if (res.code == 200) {
                    that.setData({
                        markers: res.data
                    })
                }
            })
        }
    })
}
Page({
    data: {
        width: '',
        height2: '',
        width2: '',
        height3: '',
        longitude: '',
        latitude: '',
        shutdownid: 0,
        choushui: 0,
        // cruise: 0,
        // finish: 0,
        hours: 0,
        hoursid: 0,
        minute: 0, //分
        minuteid: 0, //分
        second: 0, //秒
        secondid: 0, //秒
        startsteps: 0,
        endsteps: 0,
        steps: 0,
        length: 0,
        jbtime: '00:00:00',
        polyline: [{
            points: [],
            color: '#FF0000DD',
            width: 2,
            dottedLine: true
        }],
        points: {},
        upaddress: {},
        nvabarData: {
            showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
            title: '巡河', //导航栏 中间的标题
        },
        height: app.globalData.height * 2 + 20,
        uid: 0,
        markers: {
            // height: 30,
            // iconPath: "https://wx.qlogo.cn/mmopen/vi_32/KsE8Ql8YfG4CypViapSc9bU4GDVVQCAghPTTSNqTCrSZjScyvmNyAognlqqEvhcRyeT2SqibSTg7PEfokrzic0E7Q/132",
            // id: 0,
            // latitude: 112.938814,
            // longitude: 112.938814,
            // width: 30
        },
        cover: ''
    },
    close: function() {
        var that = this
        that.setData({
            // finish: 0,
        })
        if (that.data.shutdownid == 2) {
            that.setData({
                shutdownid: 0,
                minute: 0,
                second: 0,
                secondid: 0,
            })

        }
    },
    patrol: function() {
        wx.navigateTo({
            url: '../patrol/patrol',
        })
    },
    //关闭
    shutdown: function() {
        var that = this
        that.setData({
            // finish: 1,
            shutdownid: that.data.shutdownid,
        })
        if (wx.getStorageSync('river_id')) {
            that.setData({
                // cruise: 2,
            })
        } else {
            that.setData({
                // cruise: 1,
            })
        }
    },
    addmark: function(e) {
        wx.navigateTo({
            url: '../patrol/patrol'
        })
    },
    //开始
    begin: function() {
        var that = this
        let startaddress = ''
        wx.showLoading("开始巡河")
        that.getstartsteps()
        wx.getStorage({
            key: 'userinfo',
            success: function(e) {
                wx.getLocation({
                    type: 'gcj02', // 默认为 gcj02 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
                    success: function(r) {
                        // success 新建一条新的巡河记录
                        qqmapsdk.reverseGeocoder({
                            location: {
                                latitude: r.latitude,
                                longitude: r.longitude
                            },
                            success: function(res) {
                                startaddress = res.result.address
                                let data = {
                                    start_long: r.longitude,
                                    start_lat: r.latitude,
                                    account_id: e.data.id,
                                    startaddress: startaddress
                                }

                                var address = [{
                                    longitude: r.longitude,
                                    latitude: r.latitude
                                }];
                                var up = "polyline[0].points";
                                that.setData({ //设置并更新distance数据
                                    points: address,
                                    upaddress: address,
                                    [up]: address,
                                });
                                let url = app.globalData.resBaseUrl + app.u.river.STARTRIVER
                                api.requestUrl(data, url).then(res => {
                                    if (res.code == 200) {
                                        wx.hideLoading()
                                        that.setData({
                                            jbtime: "00:00:00",
                                            shutdownid: 1,
                                            length: 0,
                                            steps: 0,
                                            second: 0,
                                            river_id: res.data.id
                                        })
                                        wx.setStorage({
                                            key: 'river_id',
                                            data: res.data.id //存到storge中 本次巡河的id
                                        })
                                        wx.setStorageSync('start_long', r.longitude)
                                        wx.setStorageSync('start_lat', r.latitude)
                                        wx.setStorageSync('upaddress', address)
                                        wx.setStorageSync('length', 0)
                                        that.timing(that)
                                    } else {
                                        wx.hideLoading()
                                        api.showError(res.msg)
                                    }
                                });
                            },
                            fail: function() {
                                let data = {
                                    start_long: r.longitude,
                                    start_lat: r.latitude,
                                    account_id: e.data.id,
                                    startaddress: startaddress
                                }

                                var address = [{
                                    longitude: r.longitude,
                                    latitude: r.latitude
                                }];
                                var up = "polyline[0].points";
                                that.setData({ //设置并更新distance数据
                                    points: address,
                                    upaddress: address,
                                    [up]: address,
                                });
                                let url = app.globalData.resBaseUrl + app.u.river.STARTRIVER
                                api.requestUrl(data, url).then(res => {
                                    if (res.code == 200) {
                                        wx.hideLoading()
                                        that.setData({
                                            jbtime: "00:00:00",
                                            shutdownid: 1,
                                            length: 0,
                                            steps: 0,
                                            second: 0,
                                            river_id: res.data.id
                                        })
                                        wx.setStorage({
                                            key: 'river_id',
                                            data: res.data.id //存到storge中 本次巡河的id
                                        })
                                        wx.setStorageSync('start_long', r.longitude)
                                        wx.setStorageSync('start_lat', r.latitude)
                                        wx.setStorageSync('upaddress', address)
                                        wx.setStorageSync('length', 0)
                                        that.timing(that)
                                    } else {
                                        wx.hideLoading()
                                        api.showError(res.msg)
                                    }
                                });
                            }
                        });
                    },
                    fail: function() {
                        wx.hideLoading()
                        wx.getSetting({
                            success: (res) => {
                                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
                                    wx.showModal({
                                        title: '是否授权当前位置',
                                        content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                                        success: function(res) {
                                            if (res.cancel) {} else if (res.confirm) {
                                                //village_LBS(that);
                                                wx.openSetting({
                                                    success: function(data) {
                                                        if (data.authSetting["scope.userLocation"] == true) {
                                                            wx.showToast({
                                                                    title: '授权成功',
                                                                    icon: 'success',
                                                                    duration: 1000
                                                                })
                                                                //再次授权，调用getLocationt的API
                                                            village_LBS(that);
                                                        } else {
                                                            wx.showToast({
                                                                title: '授权失败',
                                                                icon: 'success',
                                                                duration: 1000
                                                            })
                                                        }
                                                    }
                                                })
                                            }
                                        }
                                    })
                                } else if (res.authSetting['scope.userLocation'] == undefined) { //初始化进入
                                    village_LBS(that);
                                }
                            }
                        })
                    }

                })
            },
            fail: function() {
                // fail
                wx.navigateTo({
                    url: '../sq/sq'
                })
            }
        })

    },
    getstartsteps: function() {
        wx.login({
            success: function(res) {
                // success
                wx.getWeRunData({
                    success: function(e) {
                        let data = {
                            code: res.code,
                            iv: e.iv,
                            encryptedData: e.encryptedData,
                            openid: wx.getStorageSync('openId')
                        }
                        let url = app.globalData.resBaseUrl + app.u.river.GETWXSTEPS
                        api.requestUrl(data, url).then(res => {
                            if (res.code == 200) {
                                wx.setStorageSync('startsteps', res.data.step)
                            } else {
                                wx.setStorageSync('startsteps', 0)
                            }
                        })
                    }
                })
            }
        })
    },
    gettimeSteps: function(that) {
        wx.login({
            success: function(res) {
                // success
                wx.getWeRunData({
                    success: function(e) {
                        let data = {
                            code: res.code,
                            iv: e.iv,
                            encryptedData: e.encryptedData,
                            openid: wx.getStorageSync('openId')
                        }
                        let url = app.globalData.resBaseUrl + app.u.river.GETWXSTEPS
                        api.requestUrl(data, url).then(res => {
                            console.log('微信运动开始')
                            if (res.code == 200) {
                                let endsteps = res.data.step
                                let startsteps = wx.getStorageSync('startsteps')
                                let steps = endsteps - startsteps
                                that.getdistance(that, steps - that.data.steps)
                                if (steps > 0) {
                                    that.setData({
                                        steps: steps
                                    })
                                }
                            } else {
                                return 0
                            }
                        })
                    },fail(e){
                        console.log('微信运动失败')
                        that.getdistance(that, 0)
                    }
                })
            }
        })
    },
    addpmark: function() {
        let that = this
        wx.getLocation({
            type: 'gcj02', // 默认为 gcj02 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function(res) {
                // success
                let data = {
                    long: res.longitude,
                    lat: res.latitude,
                    id: that.data.river_id
                }
                let url = app.globalData.resBaseUrl + app.u.river.ADDPMARK
                api.requestUrl(data, url).then(res => {})
            }
        })
    },
    //结束
    terminate: function() {
        var that = this
        let endaddress = ''
        wx.showModal({
            title: '友情提示',
            content: '确定结束巡河？',
            success: function(res) {
                if (res.confirm) {
                    clearTimeout(time);
                    wx.showLoading({
                        "title":"正在结束巡河"
                    })
                    let startsteps = wx.getStorageSync('startsteps') || 0;
                    wx.login({
                        success: function(res) {
                            // success
                            wx.getWeRunData({
                                success: function(e) {
                                    let data = {
                                        code: res.code,
                                        iv: e.iv,
                                        encryptedData: e.encryptedData,
                                        openid: wx.getStorageSync('openId')
                                    }
                                    let url = app.globalData.resBaseUrl + app.u.river.GETWXSTEPS
                                    api.requestUrl(data, url).then(res => {
                                        if (res.code == 200) {
                                            let endsteps = res.data.step
                                            let steps = endsteps - startsteps
                                            that.endcaucle(steps)
                                        } else {
                                            that.endcaucle(0)
                                            api.showError('获取微信运动失败')
                                        }
                                    })
                                },
                                fail: function(e) {
                                    that.endcaucle(0)

                                }
                            })
                        }
                    })
                } else if (res.cancel) {}
            }
        })
    },
    endcaucle: function(steps) {
        let that = this
            //获取终点位置取距离
        wx.getLocation({
            type: 'gcj02', // 默认为 gcj02 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function(r) {
                // success 新建一条新的巡河记录
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: r.latitude,
                        longitude: r.longitude
                    },
                    success: function(res) {
                        let data = {
                            end_long: r.longitude,
                            end_lat: r.latitude,
                            id: wx.getStorageSync('river_id'),
                            steps: that.data.steps,
                            length: that.data.length,
                            times: that.data.jbtime,
                            points: that.data.points,
                            account_id: wx.getStorageSync('userinfo').id,
                            seconds: that.data.second,
                            endaddress: res.result.address
                        }
                        let url = app.globalData.resBaseUrl + app.u.river.ENDRIVER
                        api.requestPostUrl(data, url).then(res => {
                            wx.hideLoading("正在结束巡河")
                            if (res.code == 200) {
                                that.setData({
                                    steps: res.data.steps,
                                    shutdownid: 2,
                                    // finish: 0,
                                    // cruise: 0,
                                })
                                api.showSuccess(res.msg)
                                wx.removeStorageSync('river_id')
                                wx.removeStorageSync('polyline')
                                wx.removeStorageSync('length')
                                clearTimeout(time);
                                setTimeout(function() {
                                    wx.navigateTo({
                                        url: '../patrollist/patrollist?id=' + res.data.id,
                                    })

                                }, 150)
                            } else {
                                api.showError(res.msg)
                            }
                        });
                    },
                    fail: function(e) {
                        let data = {
                            end_long: r.longitude,
                            end_lat: r.latitude,
                            id: wx.getStorageSync('river_id'),
                            steps: that.data.steps,
                            length: that.data.length,
                            times: that.data.jbtime,
                            points: that.data.points,
                            account_id: wx.getStorageSync('userinfo').id,
                            seconds: that.data.second,
                            endaddress: '未获取位置'
                        }
                        let url = app.globalData.resBaseUrl + app.u.river.ENDRIVER
                        api.requestPostUrl(data, url).then(res => {
                            wx.hideLoading()
                            if (res.code == 200) {
                                that.setData({
                                    steps: res.data.steps,
                                    shutdownid: 2,
                                    // finish: 0,
                                    // cruise: 1,
                                })
                                api.showSuccess(res.msg)
                                wx.removeStorageSync('river_id')
                                wx.removeStorageSync('polyline')
                                wx.removeStorageSync('length')
                            
                                // setTimeout(function() {
                                //   // wx.navigateTo({
                                //   //     url: '../filename/filename?id=' + that.data.river_id,
                                //   // })
                                wx.navigateTo({
                                        url: '../patrollist/patrollist?id=' + that.data.river_id,
                                    })
                                    // }, 1000)
                            } else {
                                api.showError(res.msg)
                            }
                        });
                    }
                });


            }
        });
    },
    conclude: function(e) {
        var that = this
        that.setData({
            // finish: 0,
            // cruise: e.currentTarget.dataset.id,
        })
    },
    //获取id实现臭水和正常水的切换功能
    choose: function(e) {
        var that = this
        that.setData({
            choushui: e.currentTarget.dataset.id,
        })
    },
    timing: function(that) {
        time = setTimeout(function() {
            let second = that.data.second + 1
            that.setData({
                jbtime: util.formatTimesecond(second),
                second: second
            })
            if (second % 5 == 0) {
                that.gettimeSteps(that)
            }
            that.timing(that)
            that.setimg()
        }, 1000)
    },
    getdistance: function(that, steps) {
        wx.getLocation({
            type: 'gcj02', // 默认为 gcj02 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function(r) {
                //调用距离计算接口
                let data = {
                    fromlat: that.data.upaddress[0].latitude,
                    fromlng: that.data.upaddress[0].longitude,
                    tolat: r.latitude,
                    tolng: r.longitude,
                    steps: steps,
                    speed: r.speed
                }
                let url = app.globalData.resBaseUrl + app.u.river.GETLENGTH
                api.requestUrl(data, url).then(res => {
                        var address = [{
                            longitude: r.longitude,
                            latitude: r.latitude
                        }];
                        var up = "polyline[0].points";
                        let length = res.data.length + that.data.length
                        if (steps == 0 && res.data.length > 0) {
                            steps = Number((res.data.length / 0.7).toFixed())

                            that.setData({
                                steps: that.data.steps + steps
                            })
                        }
                        that.setData({ //设置并更新distance数据
                            distance: length,
                            length: length,
                            points: that.data.points.concat(address),
                            upaddress: address,
                            [up]: that.data.points.concat(address),
                            longitude: r.longitude,
                            latitude: r.latitude
                        });
                        wx.setStorageSync('polyline', that.data.polyline)
                        wx.setStorageSync('upaddress', address)
                        wx.setStorageSync('length', length)
                    })
            }
        })
    },
    getriver: function(e) {
        let that = this;
        let res = [{
            points: [],
            color: '#FF0000DD',
            width: 2,
            dottedLine: true
        }]
        let polyline = wx.getStorageSync('polyline') || res
        let upaddress = wx.getStorageSync('upaddress') || {}
        let length = wx.getStorageSync('length') || 0

        let data = {
            riverid: that.data.river_id
        }
        let url = app.globalData.resBaseUrl + app.u.river.GETRIVER
        api.requestUrl(data, url).then(res => {
            if (res.code == 200) {
                that.setData({
                    // cruise: 2,
                    shutdownid: 1,
                    polyline: polyline,
                    upaddress: upaddress,
                    length: length,
                    points: polyline[0].points
                })
                that.setData({
                    time: util.formatTimesecond(res.data.remain),
                    second: res.data.remain
                })
                setTimeout(function() {
                    that.setData({
                        // finish: 1,
                    })
                }, 1000)
                that.timing(that)
            } else {
                api.showError(res.msg)
                let data = {
                    end_long: that.data.longitude,
                    end_lat: that.data.latitude,
                    id: that.data.river_id,
                    steps: 0,
                    length: length,
                    times: util.formatTimesecond(res.data.remain),
                    points: polyline[0].points,
                    account_id: wx.getStorageSync('userinfo').id,
                    seconds: res.data.remain
                }
                let url = app.globalData.resBaseUrl + app.u.river.ENDRIVER
                api.requestPostUrl(data, url).then(res => {
                    if (res.code == 200) {
                        wx.removeStorageSync('river_id')
                        wx.removeStorageSync('polyline')
                        wx.removeStorageSync('length')
                        clearTimeout(time);
                    } else {
                        api.showError(res.msg)
                    }
                });

            }

        })

    },
    article: function(e) {
        wx.navigateTo({
            url: '../article/article?id=' + e.currentTarget.id,
        })
    },
    onLoad: function() {
        var that = this
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    width: res.screenWidth * 2,
                    height2: res.screenHeight * 2,
                    width2: res.screenWidth - res.screenWidth / 750 * 220,
                    height3: res.screenHeight + res.screenHeight / 1334 * 380,
                })
            },
        })

    },
    onShow: function() {
        var that = this
        qqmapsdk = new QQMapWX({
            key: 'TTWBZ-6L56U-W55V3-BJZJ6-KGGYF-O2BRB' // 必填
        });
        wx.getStorage({
                key: 'userinfo',
                success(res) {
                    that.setData({
                        cover: res.data.cover
                    })
                }
            })
            // timer: setInterval(function() {
        wx.getLocation({
                type: 'gcj02',
                success: function(res) {
                    //   if (wx.getStorageSync('address') == '') {
                    that.setData({
                            longitude: res.longitude,
                            latitude: res.latitude,
                            markers: [{
                                iconPath: that.data.cover,
                                id: 1,
                                latitude: res.latitude,
                                longitude: res.longitude,
                                width: 30,
                                height: 30,
                            }]
                        })
                        // }else{
                        //   that.setData({
                        //     longitude: wx.getStorageSync('address').lng,
                        //     latitude: wx.getStorageSync('address').lat,
                        //     markers: [{
                        //       iconPath: that.data.cover,
                        //       id: 1,
                        //       latitude: wx.getStorageSync('address').lat,
                        //       longitude: wx.getStorageSync('address').lng,
                        //       width: 30,
                        //       height: 30,
                        //     }]
                        //   })
                        // }
                    wx.getStorage({
                        key: 'river_id',
                        success: function(res) {
                            // success
                            that.setData({
                                river_id: res.data
                            })
                            clearTimeout(time);
                            that.getriver()
                        },
                        fail: function(e) {
                            clearTimeout(time);
                        }
                    })
                },
                fail: function(e) {
                    wx.getSetting({
                        success: (res) => {
                            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
                                wx.showModal({
                                    title: '是否授权当前位置',
                                    content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                                    success: function(res) {
                                        if (res.cancel) {} else if (res.confirm) {
                                            //village_LBS(that);
                                            wx.openSetting({
                                                success: function(data) {
                                                    if (data.authSetting["scope.userLocation"] == true) {
                                                        wx.showToast({
                                                                title: '授权成功',
                                                                icon: 'success',
                                                                duration: 1000
                                                            })
                                                            //再次授权，调用getLocationt的API
                                                        village_LBS(that);
                                                    } else {
                                                        wx.showToast({
                                                            title: '授权失败',
                                                            icon: 'success',
                                                            duration: 1000
                                                        })
                                                    }
                                                }
                                            })
                                        }
                                    }
                                })
                            } else if (res.authSetting['scope.userLocation'] == undefined) { //初始化进入
                                village_LBS(that);
                            }
                        }
                    })
                }
            })
            // }, 1000)

    },
    setimg(){
        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                that.setData({
                        longitude: res.longitude,
                        latitude: res.latitude,
                        markers: [{
                            iconPath: that.data.cover,
                            id: 1,
                            latitude: res.latitude,
                            longitude: res.longitude,
                            width: 30,
                            height: 30,
                        }]
                    })
               
            }
        })
    },
    onShareAppMessage: function(res) {
        var that = this
        that.setData({
            uid: wx.getStorageSync('userinfo').id
        })
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }
        return {
            title: "我发现一个巡河神器，邀请你一起去巡河",
            path: "pages/rivercruise/rivercruise?account_id=" + that.data.uid
        }
    },
})